package com.totoro.tyrank.listener;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.InvRankTypeConst;
import com.totoro.tyrank.constants.NBTKeyConst;
import com.totoro.tyrank.constants.TagConst;
import com.totoro.tyrank.data.PlayerData;
import com.totoro.tyrank.data.RankingData;
import com.totoro.tyrank.enums.ActionEnum;
import com.totoro.tyrank.executor.action.ActionExecutor;
import com.totoro.tyrank.inventory.AttributeReceiveInventory;
import com.totoro.tyrank.inventory.RankContentInventory;
import com.totoro.tyrank.inventory.RewardReceiveInventory;
import com.totoro.tyrank.utils.DateUtil;
import com.totoro.tyrank.utils.NBTUtil;
import com.totoro.tyrank.utils.StrUtil;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class RewardReceiveInventoryListener implements Listener {

    private final List<Integer> availableRawSlots = Stream.of(49,45,53,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35).collect(Collectors.toList());

    private final Map<UUID, Long> coolDownMap = new HashMap<>();

    @EventHandler
    public void OnFire(InventoryClickEvent e) {
        Player player = (Player) e.getView().getPlayer();
        if (!RewardReceiveInventory.currentOpenReward.containsKey(player.getUniqueId())) {
            return;
        }
        String rewardInvTitle = RewardReceiveInventory.currentOpenReward.get(player.getUniqueId());
        if (e.getView().getTitle().equals(rewardInvTitle)) {
            e.setCancelled(true);
            if (!availableRawSlots.contains(e.getRawSlot())) {
                return;
            }
            // 检查冷却
            long currentTime = System.currentTimeMillis();
            if (coolDownMap.containsKey(player.getUniqueId()) &&
                    currentTime - coolDownMap.get(player.getUniqueId()) < TyRank.getConfigManager().getConfigData().getClickCooldown()) {
                player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() + TyRank.getLanguageManager().getLanguageData().getGui().getClickCooldown());
                return;
            }
            // 更新冷却时间
            coolDownMap.put(player.getUniqueId(), currentTime);

            // 获取点击物品
            ItemStack currentItem = e.getCurrentItem();
            if(null == currentItem || currentItem.getType() == Material.AIR || currentItem.getType() == Material.STAINED_GLASS_PANE) {
                return;
            }
            // 获取NBT上之前的RankType类型
            // 获取NBT上的rankId
            String rankId = "";
            String fromInvRankType = NBTUtil.getNBT(currentItem, NBTKeyConst.FROM_INV_RANK_TYPE);
            if(!StrUtil.isNotBlank(fromInvRankType)) {
                fromInvRankType = InvRankTypeConst.ALL_RANK_INV;
            }
            rankId = NBTUtil.getNBT(currentItem, NBTKeyConst.RANK_ID);
            // 获取点击类型
            ClickType clickType = e.getClick();
            Map<String, RankingData> rankDataMap = TyRank.getRankingManager().getRankDataMap();
            // 如果点击的是领取的奖励
            if(e.getRawSlot() >= 9 && e.getRawSlot() <=35) {
                if(clickType == ClickType.LEFT) {
                    // 获取名次文本
                    String rankingText = NBTUtil.getNBT(currentItem, NBTKeyConst.RANKING_TEXT);
                    // 闭榜才能领取
                    // 如果未闭榜
                    RankingData rankingData = rankDataMap.get(rankId);
                    if (DateUtil.isCurrentTimeAfter(rankingData.getEndTime())) {
                        PlayerData playerData = TyRank.getPlayerDataManager().getPlayerDataByRankId(player, rankId);
                        if (null != playerData) {
                            if (playerData.getRewardReceive()) {
                                // 已经领过了哈
                                player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                        TyRank.getLanguageManager().getLanguageData().getMsg().getRewardAlready());
                            } else {
                                // 可以领取，先获取奖励
                                RankingData.RankingReceive receive = TyRank.getRankingReceiveManager().getReceive(rankId, rankingText, playerData.getRanking());
                                if (null == receive) {
                                    player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                            TyRank.getLanguageManager().getLanguageData().getMsg().getRewardError());
                                    return;
                                }
                                RankingData.RankingReceive.Reward reward = receive.getReward();
                                if (null == reward) {
                                    player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                            TyRank.getLanguageManager().getLanguageData().getMsg().getRewardError());
                                    return;
                                }
                                // 发放奖励，然后修改玩家数据
                                playerData.setRewardReceive(true);
                                playerData.setIsClear(false);
                                if (!TyRank.getPlayerDataManager().updatePlayerData(playerData)) {
                                    player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                            TyRank.getLanguageManager().getLanguageData().getMsg().getRewardError());
                                    return;
                                }
                                // 执行奖励执行
                                List<String> actions = reward.getAction();
                                for (String action : actions) {
                                    action = action.replace(TagConst.RANK_NAME_TAG, rankingData.getRankName()).
                                            replace(TagConst.RANKING_TAG, playerData.getRanking().toString());
                                    // 获取该执行对应的接口
                                    ActionExecutor actionExecutor = ActionEnum.getExecutor(action);
                                    actionExecutor.execute(action, player);
                                }
                                RewardReceiveInventory.openMainInv(player, rankId, fromInvRankType);
                            }
                        } else {
                            // 你暂未上榜无法领
                            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                    TyRank.getLanguageManager().getLanguageData().getMsg().getRewardOff());
                        }
                    } else {
                        // 未闭榜，无法领取
                        player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                                TyRank.getLanguageManager().getLanguageData().getMsg().getRewardNotEndRank());
                    }
                }
            }

            // 如果点击的是返回
            if(e.getRawSlot() == 49) {
                AttributeReceiveInventory.currentOpenAttribute.remove(player.getUniqueId());
                AttributeReceiveInventory.currentPage.put(player.getUniqueId(), 1);
                RankContentInventory.openMainInv(player, rankId, fromInvRankType);
            }

            // 如果点击的是上一页，判断左键还是右键
            if(e.getRawSlot() == 45) {
                if(clickType == ClickType.LEFT) {
                    RewardReceiveInventory.preCurrentPage(player, rankId, fromInvRankType);
                } else if (clickType == ClickType.RIGHT) {
                    RewardReceiveInventory.firstCurrentPage(player, rankId, fromInvRankType);
                }
                return;
            }
            // 如果点击的是下一页，判断左键还是右键
            if(e.getRawSlot() == 53) {
                if(clickType == ClickType.LEFT) {
                    RewardReceiveInventory.nextCurrentPage(player, rankId, fromInvRankType);
                } else if (clickType == ClickType.RIGHT) {
                    RewardReceiveInventory.lastCurrentPage(player, rankId, fromInvRankType);
                }
                return;
            }
        }
    }
}
